<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" :model="dataForm">
          <el-form-item label="分类">
            <category-cascader :catelogPath.sync="catelogPath"  @catPath="catPathClick"></category-cascader>
          </el-form-item>
          <el-form-item label="品牌">
            <brand-select style="width:160px" :cat-path="dataForm.catelogId" @brandId="setBrandId"></brand-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select style="width:160px" v-model="dataForm.status" clearable>
              <el-option label="新建" :value="0"></el-option>
              <el-option label="上架" :value="1"></el-option>
              <el-option label="下架" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检索">
            <el-input style="width:160px" v-model="dataForm.key" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSpuInfo">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
<!--        <SpuInfo :status="dataFormSub.status" :key="dataFormSub.key" :brand-id="dataFormSub.brandId" :catelog-id="dataFormSub.catelogId" :catId="catId"></SpuInfo>-->
        <div class="mod-config">
          <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;"
          >
            <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
            <el-table-column prop="id" header-align="center" align="center" label="id" width="200"></el-table-column>
            <el-table-column prop="spuName" header-align="center" align="center" label="名称" width="200">
              <template slot-scope="scope">
                <div
                  style="height: 20px;text-overflow: ellipsis;-o-text-overflow: ellipsis;overflow: hidden;"
                  :title="scope.row.spuName">
                  {{scope.row.spuName}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="spuDescription" header-align="center" align="center" label="描述" width="200" title="fdsfds">
              <template slot-scope="scope">
                <div
                  style="height: 20px;text-overflow: ellipsis;-o-text-overflow: ellipsis;overflow: hidden;"
                  :title="scope.row.spuDescription">
                  {{scope.row.spuDescription}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="catalogId" header-align="center" align="center" label="分类" width="200"></el-table-column>
            <el-table-column prop="brandId" header-align="center" align="center" label="品牌" width="200"></el-table-column>
            <el-table-column prop="weight" header-align="center" align="center" label="重量"></el-table-column>
            <el-table-column prop="publishStatus" header-align="center" align="center" label="上架状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.publishStatus === 0">新建</el-tag>
                <el-tag v-if="scope.row.publishStatus === 1">已上架</el-tag>
                <el-tag v-if="scope.row.publishStatus === 2">已下架</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" header-align="center" align="center" label="创建时间" width="200"></el-table-column>
            <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间" width="200"></el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.publishStatus === 0"
                  type="primary"
                  size="small"
                  @click="productUp(scope.row.id)"
                >上架</el-button>
                <el-button type="success" size="small" @click="attrUpdateShow(scope.row)">规格</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 20px"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <el-dialog title="规格参数" :visible.sync="dialogFormVisible">

      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="box-card" style="margin-left:150px; width: 100%; min-height: 200px;" v-loading="loading">
            <el-tabs tab-position="top" style="width:98%" type="border-card">
              <el-tab-pane
                :label="group.attrGroupName"
                v-for="(group,gidx) in dataResp.attrGroups"
                :key="group.attrGroupId"
              >
                <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  spu.baseAttrs[0] = [{attrId:xx,val:}]-->
                <el-form ref="form" :model="dataResp">
                  <el-form-item
                    :label="attr.attrName"
                    v-for="(attr,aidx) in group.attrs"
                    :key="attr.attrId"
                  >
                    <el-input
                      v-model="dataResp.baseAttrs[gidx][aidx].attrId"
                      type="hidden"
                      v-show="false"
                    ></el-input>
                    <el-select
                      v-model="dataResp.baseAttrs[gidx][aidx].attrValues"
                      :multiple="attr.valueType === 1"
                      filterable
                      allow-create
                      default-first-option
                      placeholder="请选择或输入值"
                    >
                      <el-option
                        v-for="(val,vidx) in attr.valueSelect.split(';')"
                        :key="vidx"
                        :label="val"
                        :value="val"
                      ></el-option>
                    </el-select>
                    <el-checkbox
                      style="margin-left: 20px"
                      v-model="dataResp.baseAttrs[gidx][aidx].showDesc"
                      :true-label="1"
                      :false-label="0"
                    >快速展示</el-checkbox>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
<!--            <div style="margin:auto">-->
<!--              <el-button type="success" style="float:right" @click="submitSpuAttrs">确认修改</el-button>-->
<!--            </div>-->
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSpuAttrs">确定修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CategoryCascader from '@/components/Common/category-cascader'
import BrandSelect from "@/components/Common/brand-select"
import { listForSpu, updateAttrForSpu } from "../../../../api/goods/attr";
import { getLIstWithAttr } from "../../../../api/goods/attrgroup";
import { getList, updatePublish } from "../../../../api/goods/spu-info";
import Data from "@/views/system/dict/data";

export default {
  components: { CategoryCascader, BrandSelect },
  props: {},
  data() {
    return {
      dialogFormVisible: false,
      loading: false,
      spuId: "",
      catalogId: "",
      dataResp: {
        //后台返回的所有数据
        attrGroups: [],
        baseAttrs: []
      },
      spuAttrsMap: {},

      dataSub: null,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      catId: 0,
      catelogPath: [],
      dataForm: {
        status: "",
        key: "",
        brandId: '',
        catelogId: ''
      },
      catPathSub: null,
      brandIdSub: null

    };
  },
  computed: {},
  watch: {},
  methods: {
    text(){
      console.log(this.value1)
      console.log(typeof this.value1)
    },
    clearData(){
      this.dataResp.attrGroups = [];
      this.dataResp.baseAttrs = [];
      this.spuAttrsMap = {};
    },
    getSpuBaseAttrs() {
      listForSpu(this.spuId)
      .then((data) => {
        if(data.data.length === 0) {
          this.loading = false
        }
        data.data.forEach(item => {
          this.$set(this.spuAttrsMap, "" + item.attrId, item)
          // this.spuAttrsMap["" + item.attrId] = item;
          this.showBaseAttrs();
        })
      }).catch(()=>{})
    },
    showBaseAttrs() {
      let _this = this;
      getLIstWithAttr(this.catalogId)
      .then((data) => {
        //先对表单的baseAttrs进行初始化
        let attrArrayAll = [];
        data.data.forEach(item => {
          let attrArray = [];
          item.attrs.forEach(attr => {
            let v = "";
            if (_this.spuAttrsMap["" + attr.attrId]) {
              // if(_this.spuAttrsMap["" + attr.attrId].attrValue.indexOf(';') == -1){
              //   v = [_this.spuAttrsMap["" + attr.attrId].attrValue]
              // }else{
                v = _this.spuAttrsMap["" + attr.attrId].attrValue.split(";")
              // }
              if (v.length === 1) {
                v = v[0] + "";
              }
            }
            attrArray.push({
              attrId: attr.attrId,
              attrName: attr.attrName,
              attrValues: attr.valueType === 1 && typeof v === 'string' ? [v] : v,
              showDesc: _this.spuAttrsMap["" + attr.attrId]
                ? _this.spuAttrsMap["" + attr.attrId].quickShow
                : attr.showDesc
            })
          });
          // this.dataResp.baseAttrs.push(attrArray);
          attrArrayAll.push(attrArray)
        });
        this.$set(this.dataResp, "baseAttrs", attrArrayAll)
        this.$set(this.dataResp, "attrGroups", data.data)
        this.loading = false
        // this.dataResp.attrGroups = data.data;
      }).catch(()=>{})
    },
    submitSpuAttrs() {
      //spu_id  attr_id  attr_name             attr_value             attr_sort  quick_show
      let submitData = [];
      this.dataResp.baseAttrs.forEach(item => {
        item.forEach(attr => {
          let val = "";
          if (attr.attrValues instanceof Array) {
            val = attr.attrValues.join(";");
          } else {
            val = attr.attrValues;
          }

          if (val != "") {
            submitData.push({
              attrId: attr.attrId,
              attrName: attr.attrName,
              attrValue: val,
              quickShow: attr.showDesc
            })
          }
        })
      })
      let list = {list: submitData, spuId: this.spuId}
      console.log(list)
      this.$confirm("修改商品规格信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateAttrForSpu(list)
          .then(() => {
            this.$message({
              type: "success",
              message: "属性修改成功!"
            });
          }).catch(()=>{})
          this.dialogFormVisible = false
        })
        .catch((e) => {
          this.$message({
            type: "info",
            message: "已取消修改"+e
          });
          this.dialogFormVisible = false
        });
    },

    setBrandId(val) {
      this.dataForm.brandId = val;
    },
    catPathClick(val) {
      this.dataForm.catelogId = val[val.length-1] + '';
    },
    searchSpuInfo() {
      this.getDataList()
    },
    productUp(id) {
      updatePublish(id)
        .then(() => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.getDataList();
        }).catch()
    },
    attrUpdateShow(row) {
      this.dialogFormVisible = true
      this.loading = true
      this.spuId = row.id
      this.catalogId = row.catalogId
      this.clearData();
      this.getSpuBaseAttrs();
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      let param = {};
      Object.assign(param, this.dataForm, {
        'page': this.pageIndex,
        'limit': this.pageSize
      });
      getList(param)
        .then((data) => {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
          this.dataListLoading = false;
        }).catch(()=>{
        this.dataList = [];
        this.totalPage = 0;
        this.dataListLoading = false;
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {}
  },
  created() {
    this.getDataList()
  },
};
</script>
<style scoped>
</style>
